<template>
  <el-form ref="form" :model="user" :rules="rules" label-width="80px">
    <el-form-item label="旧密码" prop="oldPassword">
      <el-input v-model="user.oldPassword" placeholder="请输入旧密码" type="password" show-password/>
    </el-form-item>
    <el-form-item label="新密码" prop="newPassword">
      <el-input v-model="user.newPassword" placeholder="请输入新密码(必须包含大写小写英文字符 数字 特殊字符)" type="password" show-password @input="updatePasswordStrength"/>
      <div v-if="user.newPassword" class="password-strength-indicator">
        <div class="strength-text">密码强度：<span :class="strengthClass">{{ strengthText }}</span></div>
        <div class="strength-bars">
          <div class="strength-bar" :class="strengthBarClass(0)"></div>
          <div class="strength-bar" :class="strengthBarClass(1)"></div>
          <div class="strength-bar" :class="strengthBarClass(2)"></div>
        </div>
        <div class="password-requirements">
          <p>密码必须包含：</p>
          <ul>
            <li :class="{ met: hasLowercase }">至少一个小写字母 (a-z)</li>
            <li :class="{ met: hasUppercase }">至少一个大写字母 (A-Z)</li>
            <li :class="{ met: hasNumber }">至少一个数字 (0-9)</li>
            <li :class="{ met: hasSpecialChar }">至少一个特殊字符 (!@#$%^&*等)</li>
            <li :class="{ met: hasValidLength }">长度6-20个字符</li>
          </ul>
        </div>
      </div>
    </el-form-item>
    <el-form-item label="确认密码" prop="confirmPassword">
      <el-input v-model="user.confirmPassword" placeholder="请确认新密码(必须包含大写小写英文字符 数字 特殊字符)" type="password" show-password/>
    </el-form-item>
    <el-form-item>
      <el-button class="search-btn action-btn" type="primary" size="mini" @click="submit">保存</el-button>
      <el-button class="reset-btn action-btn" type="danger" size="mini"  v-if="shouldShowButton"  @click="close">关闭</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { updateUserPwd } from "@/api/system/user";

export default {
  data() {
    // 验证密码复杂度
    const validatePasswordStrength = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("新密码不能为空"));
      }

      if (value.length < 6 || value.length > 20) {
        return callback(new Error("密码长度必须在6到20个字符之间"));
      }

      // 检查是否包含非法字符
      if (/[<>"'|\\]/.test(value)) {
        return callback(new Error("不能包含非法字符：< > \" ' \\ |"));
      }

      // 检查密码复杂度要求[2,6,8](@ref)
      const hasLowercase = /[a-z]/.test(value);
      const hasUppercase = /[A-Z]/.test(value);
      const hasNumber = /\d/.test(value);
      const hasSpecialChar = /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/.test(value);

      if (!hasLowercase || !hasUppercase || !hasNumber || !hasSpecialChar) {
        return callback(new Error("密码必须包含大写字母、小写字母、数字和特殊字符"));
      }

      callback();
    };

    // 验证确认密码
    const equalToPassword = (rule, value, callback) => {
      if (this.user.newPassword !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };

    return {
      user: {
        oldPassword: undefined,
        newPassword: undefined,
        confirmPassword: undefined
      },
      passwordStrength: 0, // 0:弱, 1:中, 2:强
      strengthText: "弱",
      hasLowercase: false,
      hasUppercase: false,
      hasNumber: false,
      hasSpecialChar: false,
      hasValidLength: false,
      // 表单校验
      rules: {
        oldPassword: [
          { required: true, message: "旧密码不能为空", trigger: "blur" }
        ],
        newPassword: [
          { required: true, message: "新密码不能为空", trigger: "blur" },
          { validator: validatePasswordStrength, trigger: "blur" }
        ],
        confirmPassword: [
          { required: true, message: "确认密码不能为空", trigger: "blur" },
          { required: true, validator: equalToPassword, trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    strengthClass() {
      switch (this.passwordStrength) {
        case 0: return "strength-weak";
        case 1: return "strength-medium";
        case 2: return "strength-strong";
        default: return "strength-weak";
      }
    },
    shouldShowButton() {
      return this.$store.state.user.passwordHasUpperCase;
    }

  },
  methods: {
    // 更新密码强度显示[5](@ref)
    updatePasswordStrength() {
      if (!this.user.newPassword) {
        this.passwordStrength = 0;
        this.strengthText = "弱";
        this.resetRequirements();
        return;
      }

      // 检查各项要求
      this.hasLowercase = /[a-z]/.test(this.user.newPassword);
      this.hasUppercase = /[A-Z]/.test(this.user.newPassword);
      this.hasNumber = /\d/.test(this.user.newPassword);
      this.hasSpecialChar = /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/.test(this.user.newPassword);
      this.hasValidLength = this.user.newPassword.length >= 6 && this.user.newPassword.length <= 20;

      // 计算密码强度[5,7](@ref)
      const requirementsMet = [
        this.hasLowercase,
        this.hasUppercase,
        this.hasNumber,
        this.hasSpecialChar,
        this.hasValidLength
      ].filter(Boolean).length;

      if (requirementsMet <= 2) {
        this.passwordStrength = 0;
        this.strengthText = "弱";
      } else if (requirementsMet === 3 || requirementsMet === 4) {
        this.passwordStrength = 1;
        this.strengthText = "中";
      } else {
        this.passwordStrength = 2;
        this.strengthText = "强";
      }
    },

    // 重置要求状态
    resetRequirements() {
      this.hasLowercase = false;
      this.hasUppercase = false;
      this.hasNumber = false;
      this.hasSpecialChar = false;
      this.hasValidLength = false;
    },

    // 密码强度条样式[3,4](@ref)
    strengthBarClass(barIndex) {
      if (barIndex <= this.passwordStrength) {
        switch (this.passwordStrength) {
          case 0: return "weak";
          case 1: return "medium";
          case 2: return "strong";
          default: return "";
        }
      }
      return "";
    },

    submit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 提交前再次验证密码强度
          const hasLowercase = /[a-z]/.test(this.user.newPassword);
          const hasUppercase = /[A-Z]/.test(this.user.newPassword);
          const hasNumber = /\d/.test(this.user.newPassword);
          const hasSpecialChar = /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/.test(this.user.newPassword);

          if (!hasLowercase || !hasUppercase || !hasNumber || !hasSpecialChar) {
            this.$modal.msgError("密码必须包含大写字母、小写字母、数字和特殊字符");
            return;
          }

          updateUserPwd(this.user.oldPassword, this.user.newPassword).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.$store.dispatch('LogOut').then(() => {
              location.href = '/index';
            })
          });
        }
      });
    },

    close() {
      this.$tab.closePage();
    }
  }
};
</script>

<style scoped>
::v-deep .el-button {
  min-width: 120px;
  height: 40px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  letter-spacing: 1px;
  transition: all 0.3s;
  margin: 0;
  margin-right: 10px;
}

/* 搜索按钮 - 宝石蓝渐变 */
::v-deep .el-form-item .search-btn {
  background: linear-gradient(135deg, #b4cdeb, #2f6bcc);
  color: #fff;
  border: none;
}
::v-deep .el-form-item .search-btn:hover {
  background: linear-gradient(135deg, #5aa2f8, #3a8ef6);
  box-shadow: 0 6px 14px rgba(58, 142, 246, 0.5);
  border: none;
}

/* 重置按钮 - 高级灰蓝 */
::v-deep .el-form-item .reset-btn {
  background: linear-gradient(135deg, #df9f3f, #edc73d);
  color: #fff;
  border: none;
}
::v-deep .el-form-item .reset-btn:hover {
  background: linear-gradient(135deg, #ffcc80, #ffb74d);
  box-shadow: 0 6px 14px rgba(255, 183, 77, 0.5);
  border: none;
}

/* 密码强度指示器 */
.password-strength-indicator {
  margin-top: 10px;
  padding: 10px;
  background-color: #2681fd;
  border-radius: 4px;
}

.strength-text {
  font-size: 14px;
  margin-bottom: 8px;
}

.strength-weak {
  color: #f56c6c;
  font-weight: bold;
}

.strength-medium {
  color: #e6a23c;
  font-weight: bold;
}

.strength-strong {
  color: #67c23a;
  font-weight: bold;
}

.strength-bars {
  display: flex;
  gap: 4px;
  margin-bottom: 10px;
}

.strength-bar {
  height: 4px;
  flex: 1;
  background-color: #dcdfe6;
  border-radius: 2px;
  transition: all 0.3s;
}

.strength-bar.weak {
  background-color: #f56c6c;
}

.strength-bar.medium {
  background-color: #e6a23c;
}

.strength-bar.strong {
  background-color: #67c23a;
}

.password-requirements {
  font-size: 12px;
  color: #606266;
}

.password-requirements p {
  margin: 5px 0;
  font-weight: bold;
  color: #e6e6e6;
}

.password-requirements ul {
  list-style: none;
  padding: 0;
  margin: 5px 0;
  color: #e6e6e6;
}

.password-requirements li {
  padding: 2px 0;
  position: relative;
  padding-left: 15px;
}

.password-requirements li:before {
  content: "✗";
  position: absolute;
  left: 0;
  color: #f56c6c;
}

.password-requirements li.met:before {
  content: "✓";
  color: #67c23a;
}
</style>
